<template>
  <div style="width: 100%; height: 100%">
    <!-- 指挥中心---事件列表 -->
    <el-container class="home-qyda" v-if="showlist" v-loading="loading">
      <el-header class="header search-header">
        <el-form
          ref="ruleFormRef"
          class="between-form"
          :model="search"
          :inline="true"
        >
          <div style="flex: 1">
            <el-form-item label="事件类型" prop="eventCode">
              <el-select
                v-model="search.eventCode"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sjlx"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事件等级" prop="eventClass">
              <el-select
                v-model="search.eventClass"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sjdj"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属社区" prop="orgId">
              <el-select
                v-model="search.orgId"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sssq"
                  :key="item.orgId"
                  :label="item.orgName"
                  :value="item.orgId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事件状态" prop="eventStatus">
              <el-select
                v-model="search.eventStatus"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sjzt"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事件来源" prop="eventSource">
              <el-select
                v-model="search.eventSource"
                placeholder="请选择"
                style="min-width: 120px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in typeState.sjly"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事件时间" prop="eventTime">
              <el-date-picker
                style="width: 340px"
                v-model="search.eventTime"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleEventTimeChange"
              />
            </el-form-item>
          </div>
          <div style="width: 250px">
            <el-form-item>
              <el-button
                type="primary"
                class="search-btn"
                @click="getSearch(ruleFormRef)"
              >
                查询
              </el-button>
              <el-button @click="reset(ruleFormRef)" class="reset-btn"
                >重置</el-button
              >
            </el-form-item>
          </div>
        </el-form>
      </el-header>
      <el-header class="header">
        <div class="header-l">
          <el-icon color="#2263BF">
            <Operation />
          </el-icon>
          <span class="text">事件列表</span>
        </div>
        <div class="header-r">
          <!-- <el-button
            link
            type="primary"
            class="self_btns"
            :disabled="selected.length === 0"
            @click="deleteRow(selected)"
            v-if="leaderList.indexOf(UserId) > -1"
          >
            <img
              style="margin-right: 10px"
              src="../../assets/images/plsc.png"
            />批量删除
          </el-button> -->
          <el-button
            link
            type="primary"
            class="self_btns"
            :disabled="selected.length === 0"
            @click="saveExport"
          >
            <img
              style="margin-right: 10px"
              src="../../assets/images/pldc.png"
            />批量导出
          </el-button>
        </div>
      </el-header>
      <el-main>
        <el-container>
          <el-main>
            <el-container>
              <el-main class="container bc-table">
                <el-table
                  :data="objecInfo.tableData"
                  style="width: 100%; height: 100%"
                  @selectionChange="changeSelect"
                  row-key="busizEventId"
                >
                  <el-table-column type="selection" width="55" />
                  <el-table-column
                    prop="busizEventId"
                    label="事件编号"
                    width="200"
                  />
                  <el-table-column
                    prop="address"
                    label="事件地址"
                    width="150px"
                  />
                  <el-table-column prop="eventName" label="事件类型" />
                  <el-table-column prop="eventClass" label="事件等级">
                    <template #default="scope">
                      <span
                        class="level z"
                        v-if="scope.row.eventClass == '重点'"
                        >重点</span
                      >
                      <span
                        class="level w"
                        v-else-if="scope.row.eventClass == '紧急'"
                        >紧急</span
                      >
                      <span class="level" v-else>普通</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="orgName" label="所属社区">
                  </el-table-column>
                  <el-table-column prop="eventSource" label="事件来源">
                  </el-table-column>
                  <el-table-column prop="reporter" label="上报人">
                    <template #default="scope">
                      <span
                        >{{ scope.row.reporter ? scope.row.reporter : "-" }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="eventStatus" label="事件状态">
                    <template #default="scope">
                      <span
                        style="color: #ff9e21"
                        v-if="scope.row.eventStatusCode == '0'"
                        >{{ scope.row.eventStatus }}</span
                      >
                      <span
                        style="color: #ae21ff"
                        v-else-if="scope.row.eventStatusCode == '10'"
                        >{{ scope.row.eventStatus }}</span
                      >
                      <span
                        style="color: #2aba77"
                        v-else-if="scope.row.eventStatusCode == '99'"
                        >{{ scope.row.eventStatus }}</span
                      >
                    </template>
                  </el-table-column>
                  <el-table-column prop="assignedMember" label="处置人员">
                    <template #default="scope">
                      <span
                        >{{
                          scope.row.assignedMember
                            ? scope.row.assignedMember
                            : "-"
                        }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="eventTime"
                    label="事件时间"
                    width="200px"
                  >
                    <template #default="scope">
                      <!-- <span
                        >{{ scope.row.eventTimeStart }}-{{
                          scope.row.eventTimeEnd
                        }}</span
                      > -->
                      <span>{{ formatDateTime(scope.row.eventTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        size="small"
                        @click="seedetail(scope.row)"
                        >详情</el-button
                      >
                      <!-- <el-button
                        v-if="leaderList.indexOf(UserId) > -1"
                        link
                        type="primary"
                        size="small"
                        @click="deleteRow([scope.row.busizEventId])"
                        >删除</el-button
                      > -->
                    </template>
                  </el-table-column>
                </el-table>
              </el-main>
              <el-footer class="footer mt20">
                <el-pagination
                  v-model:current-page="tableField.pageNo"
                  v-model:page-size="tableField.pageSize"
                  :page-sizes="[10, 20, 30, 50, 100]"
                  layout="total,sizes, prev, pager, next, jumper"
                  :total="total"
                  :background="true"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  prev-text="上一页"
                  next-text="下一页"
                />
              </el-footer>
            </el-container>
          </el-main>
        </el-container>
      </el-main>
    </el-container>
    <!-- 删除 -->
    <SelfDialog
      :dialogVisable="dialogVisable"
      height="320px"
      title="提示"
      @close="close"
      @confirm="confirm"
    >
      <template #default>
        <div class="center_content">
          <img class="icon-img" src="../../assets/images/gth.png" />
          <p class="text">是否确认删除，删除后无法撤回</p>
        </div>
      </template>
    </SelfDialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { onMounted, ref, reactive, watch, onActivated } from "vue";
import { getEventList } from "@/api/event";
import { Minxfun } from "@/utils/minxin";
import SelfDialog from "@/components/dialog/dialog.vue";

import { TypeMin } from "@/utils/type.js";

const { typeState } = TypeMin();

import { TabbarList } from "@/pinia/tabbar.js";
let piniaTab = TabbarList();
import dayjs from "dayjs";

const {
  handleSizeChange,
  handleCurrentChange,
  tableField,
  total,
  loading,
  formatDateTime,
} = Minxfun();
import { useUserStore } from "@/pinia/user.js";
const piniaUser = useUserStore();
const UserId = localStorage.getItem("User");
// 需要根据权限判断是否显示
//领导是数组list 科员队员的数组list
const leaderList = [
  "1903999283762434048",
  "1903999283762434049",
  "1903999283766628353",
  "1903999283766628355",
];
const memberList = [
  "1903999283766628352",
  "1903999283766628354",
  "1903999283766628356",
];
const ruleFormRef = ref();
const search = reactive({
  eventCode: "",
  eventStatus: "",
  eventClass: "",
  eventTime: [],
  deviceId: "",
  orgId: "",
  assignedMemberId: "",
  handleTime: "",
  eventSource: "",
  purpose: "D", //非z和c的任意一个，以及不能是空，差的待指派+待处置+完成
});

let selected = ref([]);

const changeSelect = (rows) => {
  selected.value = rows;
};

onActivated(() => {
  // 组件激活时重新获取数据
  getTableData();
});

onMounted(() => {
  // getType();
  getTableData();
});

// 获取部门
let doorList = ref([]);
let sortList = ref([]);
const getType = async () => {
  try {
    let res1 = await industrycategory();
    sortList.value = res1.data;
  } catch (e) {
    console.log(e);
  }
};

const getSearch = () => {
  if (tableField.value.pageNo == 1) {
    getTableData();
  } else {
    tableField.value.pageNo = 1;
    getTableData();
  }
};

const reset = (ruleFormRef) => {
  ruleFormRef.resetFields();
  search.eventTime = [];
  getTableData();
};

watch(
  tableField,
  (newVal, oldVal) => {
    getTableData();
  },
  { deep: true }
);
let objecInfo = reactive({
  tableData: [],
});
const handleEventTimeChange = (value) => {
  if (value === null) {
    // 清空时重置为 []
    search.eventTime = [];
  } else {
    search.eventTime = value;
  }
  // 重新加载数据
  getTableData();
};
const getTableData = async () => {
  try {
    loading.value = true;
    // 确保 eventTime 和 assessTime 是数组类型（默认为 []）
    search.eventTime = search.eventTime || [];
    let obj = {
      ...tableField.value,
      ...search,
      pageNum: tableField.value.pageNo,
      eventTimeStart:
        search.eventTime.length > 0
          ? dayjs(search.eventTime[0]).format("YYYY-MM-DD HH:mm:ss")
          : "",
      eventTimeEnd:
        search.eventTime.length > 0
          ? dayjs(search.eventTime[1]).format("YYYY-MM-DD HH:mm:ss")
          : "",
    };

    let { data } = await getEventList(obj);
    loading.value = false;
    objecInfo.tableData = data.busizEventList;
    total.value = Number(data.total) || 0;
  } catch (e) {
    loading.value = false;
    console.error(e);
  }
};

let currentRow = ref(null);
let showDetail = ref(false);
const handleClick = (value) => {
  currentRow.value = value;
  showDetail.value = true;
};

// 删除
let dialogVisable = ref(false);
let deletList = ref([]);
const deleteRow = (value) => {
  try {
    dialogVisable.value = true;
    deletList.value = value;
  } catch (e) {
    console.error(e);
  }
};

// 取消删除
const close = () => {
  dialogVisable.value = false;
};

// 确认删除
const confirm = async () => {
  try {
    // let { data } = await delfl({
    //   busiTypeCode: deletList.value,
    // });
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    getTableData();
    dialogVisable.value = false;
  } catch (e) {
    console.error(e);
  }
};

// 导出
const saveExport = async () => {
  try {
    // exportVisable.value = false;
    console.log(fieldList.value);
    let params = {
      objectId: currentTab.value,
      queryOptions: searchData.value,
      orderBys: sortList.value,
      selectItems: fieldList.value.map((item) => item.props),
    };
    let config = {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        "Access-Control-Allow-Origin": true,
        withCredentials: true,
        "Access-Control-Expose-Headers": "Authorization",
      },
      responseType: "blob",
    };
    axios
      .post("/data-center/query/composite/export", params, config)
      .then((res) => {
        window.open(res.data.data.fileUrl);
        // const content = res.data;
        // const blob = new Blob([content]);
        // const fileName =
        //   decodeURI(
        //     res.headers["content-disposition"].split(";")[1].split("=")[1]
        //   ) || "文件.xlsx";
        // if ("download" in document.createElement("a")) {
        //   // 非IE下载
        //   const elink = document.createElement("a");
        //   elink.download = fileName;
        //   elink.style.display = "none";
        //   elink.href = URL.createObjectURL(blob);
        //   document.body.appendChild(elink);
        //   elink.click();
        //   URL.revokeObjectURL(elink.href); // 释放URL 对象
        //   document.body.removeChild(elink);
        // } else {
        //   // IE10+下载
        //   navigator.msSaveBlob(blob, fileName);
        // }
      });
  } catch (e) {}
};

const seedetail = (row) => {
  console.log("ssssssssssssssssssssssssss", row);
  // eventStatusCode 99=已完成，10=待处置，0=待指派
  if (row.eventStatusCode == "0") {
    piniaTab.add({
      name: "指派详情",
      path: "/fpdetail",
      icon: "",
      query: {
        busizEventId: row.busizEventId,
      },
      meta: {
        hidden: false,
        title: "",
      },
    });
  } else if (row.eventStatusCode == "10") {
    piniaTab.add({
      name: "处置详情",
      path: "/czdetail",
      icon: "",
      query: {
        busizEventId: row.busizEventId,
      },
      meta: {
        hidden: false,
        title: "",
      },
    });
  } else if (row.eventStatusCode == "99") {
    piniaTab.add({
      name: "事件详情",
      path: "/eventdetail",
      icon: "",
      query: {
        busizEventId: row.busizEventId,
      },
      meta: {
        hidden: false,
        title: "",
      },
    });
  } else {
    ElMessage({
      message: "接口返回数据状态值异常",
      type: "error",
    });
    return;
  }
};

// 展示详情
let showlist = ref(true);
let currentData = ref(null);
const changeStatus = (value) => {
  if (value) {
    currentData.value = value;
  } else {
    currentData.value = null;
  }
  showlist.value = !showlist.value;
};
</script>

<style lang="scss" scoped>
.home-qyda {
  width: 100%;
  height: 100%;

  .header {
    min-height: 36px;
    line-height: 36px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    overflow: hidden;
    margin-bottom: 18px;

    .header-l {
      display: flex;
      align-items: center;

      .text {
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 16px;
        color: #333333;
        line-height: 22px;
        letter-spacing: 1px;
        text-align: left;
        padding-left: 14px;
      }
    }
  }
}

.el-container {
  height: 100% !important;
  padding: 0 !important;
}

.el-header {
  height: auto !important;
  min-height: 36px !important;
}

.el-main {
  padding: 0 !important;
}

.search {
  margin: 0 50px;
}

.header-r {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 14px;
  color: #666666;
}
</style>

<style lang="scss">
.el-form-item__label {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 14px;
  color: #333333;
}

.self_btns {
  color: #2263bf !important;
}

.level {
  display: inline-block;
  text-align: center;
  width: 60px;
  height: 26px;
  background: #e7f6ff;
  border-radius: 4px;
  border: 1px solid rgba(47, 173, 255, 0.32);
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #21adff;
  line-height: 26px;

  &.w {
    background: #ffe6e6;
    color: #ff2121;
    border: 1px solid rgba(255, 47, 47, 0.32);
  }

  &.z {
    background: #fff4e8;
    color: rgba(255, 160, 47, 1);
    border: 1px solid rgba(255, 160, 47, 0.32);
  }
}
</style>
